//
//  PDFWebView.m
//  PDFJSReader
//
//  Created by lilu on 2017/5/12.
//  Copyright © 2017年 lilu. All rights reserved.
//

#import "PDFWebView.h"

@interface PDFWebView () <UIGestureRecognizerDelegate>
{
    NSInteger _pageNumber;
}
@end

@implementation PDFWebView
- (void)dealloc{
    
    NSLog(@"%s", __func__);
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.startPageNumber = 1;
        self.scrollView.bounces = NO;
       
        
    }
    return self;
}

- (void)loadPDFFile:(NSString*)filePath;{
    _filePath = filePath;

    NSURLRequest *request = [NSURLRequest requestWithURL:[self getLocalHtmlUrl:filePath]];
    [self loadRequest:request];
    
}

- (void)setPageNumber:(NSInteger)pageNumber{
    _pageNumber = pageNumber;
    NSString *string = [NSString stringWithFormat:@"window.PDFViewerApplication.page = %zd", pageNumber];
    [self evaluateJavaScript:string completionHandler:nil];
}

/**
 关闭pdf
 */
- (void)closePdf{
    NSString *string = @"window.PDFViewerApplication.close();";
    [self evaluateJavaScript:string completionHandler:nil];
}

- (NSURL *)getLocalHtmlUrl:(NSString *)filePath{
    
    NSString *pdfjsDirectory = [[NSBundle mainBundle] pathForResource:@"PDFJS" ofType:nil];
    NSString *htmlPath = [pdfjsDirectory stringByAppendingString:@"/web/viewer.html"];
    
    //pdf文件先移到沙盒(必须是tmp目录)
    filePath = [self copyFileToSanBoxTmp:filePath handler:nil];
    
    NSString *htmlUrlString = [@"file://" stringByAppendingString:htmlPath];
    
    filePath = [NSString stringWithFormat:@"file://%@", filePath];
    NSString *urlString = [NSString stringWithFormat:@"%@?file=%@#page=%zd", htmlUrlString, filePath, self.startPageNumber];
    
    urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *URL = [NSURL URLWithString:urlString];
    
    NSLog(@"URL:%@", URL);
    return URL;
    
}

#pragma mark - 将文件拷贝到沙盒
///将文件拷贝到沙盒
- (NSString *)copyFileToSanBoxTmp:(NSString *)filepath handler:(void(^)(BOOL))handler{
    NSString *tmp = NSTemporaryDirectory();
    NSString *filename = [[filepath componentsSeparatedByString:@"/"] lastObject];
    if (!filename) {
        filename = filepath;
    }
    
    NSString *dataPath = [tmp stringByAppendingString:filename];
    
    BOOL success = NO;
    NSError *error = nil;
    //源文件
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
        success = [[NSFileManager defaultManager] copyItemAtPath:filepath toPath:dataPath error:&error];
    }
    success = YES;
    handler ? handler(success) : nil;
    return dataPath;
    
}

@end
